package com.pinusmusic.service.impl;

import com.pinusmusic.dao.MusicListDao;
import com.pinusmusic.dao.Music_MusicListDao;
import com.pinusmusic.dao.UserDao;
import com.pinusmusic.dao.impl.MusicListDaoImpl;
import com.pinusmusic.dao.impl.Music_MusicListDaoImpl;
import com.pinusmusic.dao.impl.UserDaoImpl;
import com.pinusmusic.domain.*;
import com.pinusmusic.service.MusicListService;
import com.pinusmusic.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;


public class MusicListServiceImpl implements MusicListService {
    private MusicListDao musicListDao = new MusicListDaoImpl();
    private UserDao userDao=new UserDaoImpl();
    private Music_MusicListDao music_musicList = new Music_MusicListDaoImpl();
    private UserService us = new UserServiceImpl();
    // 1.创建磁盘文件项工厂
    private DiskFileItemFactory factory = new DiskFileItemFactory();
    // 2.创建文件上传的核心类
    private ServletFileUpload upload = new ServletFileUpload(factory);
    @Override
    public void addMusicList(MusicList addMusicList) {
        musicListDao.addMusicList(addMusicList);
    }

    @Override
    public void deleteMusicListAndMusicByMlid(int mlid) {
         int count = music_musicList.getMusicCountByMlid(mlid);
         if (count>0){
             music_musicList.deleteMusicByMlid(mlid);
         }
         musicListDao.deleteMusicListById(mlid);
    }

    @Override
    public boolean updateMusicList(MusicList updateMusicList) {
       return musicListDao.updateMusicList(updateMusicList);
    }

    @Override
    public MusicList findMusicListByMlid(int mlid) {
        return musicListDao.findMusicListByMlid(mlid);
    }

    @Override
    public PageBean<MusicList> findMusicListByPage(int currentPage, int rows) {
        PageBean<MusicList> pageBean = new PageBean<>();
        //1.设置总数
        int totalCount = musicListDao.getTotalCount();
        pageBean.setTotalCount(totalCount);
        //2.设置总页码
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        //3.设置当前页码数,设置边界值
        if (currentPage<=0) currentPage=1;
        if (currentPage>=totalPage && totalPage>0) currentPage=totalPage;
        pageBean.setCurrentPage(currentPage);
        //4.设置每页显示条数
        pageBean.setPageSize(rows);
        //5.设置对应数据
        int start = (currentPage-1)*rows;
        List<MusicList> musicLists = musicListDao.findMusicListByPage(start,rows);
        pageBean.setList(musicLists);
        return pageBean;
    }

    @Override
    public void deleteMoreMusicList(String[] mlids) {
        if (mlids==null) return;
        for (String mlid:mlids) deleteMusicListAndMusicByMlid(Integer.parseInt(mlid));
    }

    @Override
    public void addMusic(int mlid, int mid) {
        boolean flag = music_musicList.findMusicByMlidAndMid(mlid,mid);
        if (flag){
            music_musicList.addMusic(mlid,mid);
        }
    }

    @Override
    public List<Integer> findMusicByMlid(int mlid) {
        return music_musicList.findMusicByMlid(mlid);
    }

    @Override
    public void addMoreMusicToList(String[] mids, Integer mlid) {
        if (mids==null) return;
        for (String mid:mids) addMusic(mlid,Integer.parseInt(mid));
    }

    @Override
    public void remMusic(Integer mlid, int mid) {
        music_musicList.remMusic(mlid,mid);
    }

    @Override
    public void remMoreMusic(String[] mids, Integer mlid) {
        if (mids==null) return;
        for (String mid:mids) remMusic(mlid,Integer.parseInt(mid));
    }

    @Override
    public MusicList getAddMusicList(HttpServletRequest request) throws IOException {
        MusicList addMusicList = new MusicList();
        String filepath = "";
        String imgname = "";
        String imgpath = "";

        List<FileItem> list = null;
        try {
            list = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        for (FileItem item : list) {
            boolean formField = item.isFormField();// 是否是一个普通表单项
            if (formField) {
                // 普通表单项
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("utf-8");
                System.out.println("上传的是普通表单项" + fieldName + "---" + fieldValue);
                if (fieldName.equals("musiclistname")) {
                    addMusicList.setMusiclistname(fieldValue);
                } else {
                    return null;
                }
            } else {
                // 文件上传项
                //共4项   (短)imgname filename imgpath filepath(长)
                imgname = item.getName();
                //zjl.jpg
                //获得的文件名至少为%.%,若长度小于3则无效不写入
                if (imgname.length() >= 3) {
                    InputStream in = item.getInputStream();
                    String path = request.getServletContext().getRealPath("images");
                    String filename = UUID.randomUUID() + imgname;
                    //f43910b7-b9f8-4f48-affe-79ccefbeeceezjl.jpg
                    System.out.println("服务器上图片文件名是" + filename);
                    imgname = imgname.substring(0, imgname.lastIndexOf("."));
                    //zjl
                    System.out.println("要存进数据库的图片名是" + imgname);
                    filepath = path + "\\" + filename;
                    //F:\Java\pinusmusic\src\main\webapp\images\f43910b7-b9f8-4f48-affe-79ccefbeeceezjl.jpg
                    imgpath = filepath.substring(filepath.lastIndexOf("webapp\\") + 7);
                    //images\f43910b7-b9f8-4f48-affe-79ccefbeeceezjl.jpg
                    System.out.println("要存进数据库的图片文件路径是" + imgpath);
                    System.out.println("上传图片文件路径是" + filepath);

                    //复制到资源文件夹
                    OutputStream out = new FileOutputStream(filepath);
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    in.close();
                    out.close();
                    addMusicList.setMusiclistimg(imgpath);
                } else {
                    return null;
                }
            }
        }
        return addMusicList;
    }

    @Override
    public ResultInfo getUpdateMusicList(HttpServletRequest request) throws IOException {
        boolean flag = false;//是否成功更新到webapp内
        String errorMsg = "";
        String filepath = "";
        MusicList musicList = new MusicList();
        MusicList musicList1 = (MusicList) request.getSession().getAttribute("musicList");
        musicList.setMlid(musicList1.getMlid());
        // 3.解析request-获得文件项集合
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        // 4.遍历文件项集合,并记录需要写入数据库的信息
        for (FileItem item : list) {
            boolean formField = item.isFormField();// 是否是一个普通表单项
            if (formField) {
                // 普通表单项
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("utf-8");
                if (fieldName.equals("musiclistname")) {
                    musicList.setMusiclistname(fieldValue);
                } else if (fieldName.equals("mlid")) {
                } else{ break; }
            } else {

                // 文件上传项
                // 获得上传文件的名称
                String imgName = item.getName();
                //覆潮之下.mp3
                String imgPath = null;


                if(imgName==null||imgName.equals("")){
                    flag=true;
                    musicList.setMusiclistimg(musicListDao.findPathByMlid(musicList1.getMlid()));
                    errorMsg="未传入文件，保留原文件";
                    System.out.println(errorMsg);
                }
                else{
                    //获得的文件名至少为%.%,若长度小于3则无效不写入
                    if (imgName.length() >= 3) {
                        InputStream in = item.getInputStream();
                        String path = request.getServletContext().getRealPath("images");
                        String filename = UUID.randomUUID() + imgName;
                        //f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
//                    System.out.println("服务器上音乐文件名是"+filename);
                        imgName = imgName.substring(0, imgName.lastIndexOf("."));
                        filepath = path + "\\" + filename;
                        //F:\Java\pinusmusic\src\main\webapp\music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                        imgPath = filepath.substring(filepath.lastIndexOf("webapp\\") + 7);
                        //music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                       // System.out.println("要存进数据库的音乐文件路径是" + imgPath);
//                    System.out.println("上传音乐文件路径是" + filepath);


                        musicList.setMusiclistimg(imgPath);

                        //复制到资源文件夹
                        OutputStream out = new FileOutputStream(filepath);
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        in.close();
                        out.close();
                    } else {
                        errorMsg = "上传的文件名不正确";
                        break;
                    }

                    String delimgpath = musicListDao.findPathByMlid(musicList.getMlid());
                    if (delimgpath != null) {
                        File file = new File(delimgpath);
                        file.delete();
                    } else {
                        break;
                    }

                }
                //将音乐文件名和可使用的音乐文件路径写入数据库
                if (musicListDao.updateMusicList(musicList)) {
                    flag = true;
                } else {
                    errorMsg = "更新数据库记录时发生错误";
                    break;
                }
            }
        }

        //返回json信息
        ResultInfo info = new ResultInfo();
        info.setFlag(flag);
        if (!flag) {
            info.setErrorMsg(errorMsg);
        } else {
            info.setData(filepath);
            info.setErrorMsg("写入成功");
        }
        return info;
    }

    @Override
    public int getCountByUid(int uid) {
        return musicListDao.getCountByUid(uid);
    }

    @Override
    public PageBean<MusicList> findMusicListsByName(int currentPage, int rows, String name) {
        PageBean<MusicList> pageBean = new PageBean<>();
        //2.获取总记录数
        int totalCount = musicListDao.getLikeCount(name);
        pageBean.setTotalCount(totalCount);
        //3.设置总页码数
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        //4.设置当前页码数,设置边界值
        if (currentPage<=0) currentPage=1;
        if (currentPage>=totalPage && totalPage>0) currentPage=totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        //6.设置对应数据
        int start =(currentPage-1)*rows;
        List<MusicList> lists = musicListDao.findMusicListsByName(start, rows, name);
        if (lists!=null){
            //获取歌单创建人
            for (int i = 0; i < lists.size(); i++) {
                //通过Createrid查找用户名
                Integer uid = lists.get(i).getCreaterid();
                User user = us.findUserById(uid);
                lists.get(i).setUser(user);
            }
        }
        pageBean.setList(lists);
        return pageBean;
    }

    //2.0
    @Override
    public MusicList findMusiclistAndCreatorByMlid(int mlid) {
        MusicList musiclistwithcreator;
        musiclistwithcreator=musicListDao.findMusicListByMlid(mlid);
        musiclistwithcreator.setUser(userDao.findUserById(musicListDao.findCreatorIdByMlid(mlid)));
        return musiclistwithcreator;
    }

    @Override
    public List<MusicList> findCreationlistByUid(int uid) {
        return musicListDao.findCreationlistByUid(uid);
    }

    @Override
    public List<MusicList> findCollectedlistByUid(int uid) {
        return musicListDao.findCollectedlistByUid(uid);
    }

    @Override
    public void cancelCollectByMlid(int mlid,int uid) {
        musicListDao.cancelCollectByMlid(mlid,uid);
    }

    @Override
    public boolean createListAndAdd(String musiclistname, Integer uid,int mid) {
        boolean isExist = musicListDao.isExistByMusiclistnameAndUid(musiclistname,uid);
        //用户输入的歌单名，是他没有的
        if (isExist){
            //创建歌单
            musicListDao.createList(musiclistname,uid);
            //获取刚刚创建的歌单
            MusicList musicList = musicListDao.findMusicListByMusiclistName(musiclistname,uid);
            //给歌单添加歌曲
            addMusic(musicList.getMlid(),mid);
        }
        return isExist;
    }
    @Override
    public void collectByMlid(int mlid, int uid) {
        if(!musicListDao.isCollected(mlid,uid)){
            musicListDao.collectByMlid(mlid,uid);
            System.out.println("收藏成功");
        }else {
            System.out.println("已被收藏");
        }
    }
}
